import qs from "qs";

export const sFetch = (
  url: string,
  method: string = "get",
  data: any = {},
  isFile: boolean = false,
  signal?: any
) => {
  return new Promise<any>((resolve, reject) => {
    let params = "";
    let body = "";
    let option = {} as any;

    if (method === "get") {
      params = qs.stringify(data);
      option = {
        method: method,
        signal: signal,
      };
    } else if (method === "post") {
      if (!isFile) {
        body = JSON.stringify(data);
        option = {
          method: method.toUpperCase(),
          body: body,
          headers: {
            "Content-Type": "application/json",
          },
          signal: signal,
        };
      } else {
        option = {
          method: method.toUpperCase(),
          body: data,
          signal: signal,
        };
      }
    }
    try {
      fetch(method === "get" ? url + "?" + params : url, option)
        .then((response) => {
          return response.json();
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          if (err.name === "AbortError") {
            // 请求被取消
            // console.log("GET请求被取消");
            reject("request abort");
          } else {
            // 其他错误
            console.error("发生错误", err);
            reject(err);
          }
        });
    } catch (error) {
      reject(error);
    }
  });
};
